package com.ikas.autumn.iec104.module.iec;

import org.openmuc.j60870.ClientConnectionBuilder;
import org.openmuc.j60870.Connection;

import java.io.IOException;
import java.net.InetAddress;

//由于可能要监听多个从站，这里使用多线程处理
public class J60870Client implements Runnable {

	//监听类，后面代码会给出
	private J60870ClientListener listener;
	//连接类
	private Connection connection;
	//连接参数，可以配置的参数有好多，比如t0,t1,t2等等
	private ClientConnectionBuilder clientConnectionBuilder;

	public J60870Client() throws IOException{
		try {
			//获取server端、从站的ip地址对象，这里使用本地ip
			InetAddress address = InetAddress.getByName("127.0.0.1");
			//创建连接参数对象
			clientConnectionBuilder = new ClientConnectionBuilder(address);
			//设置socket的连接超时时间
			clientConnectionBuilder.setConnectionTimeout(60000);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	//Runnable的run方法重写
	public void run() {
		try {
			//主站与从站连接
			connection = clientConnectionBuilder.build();
			//配置数据回调类
			listener = new J60870ClientListener();
			connection.startDataTransfer(listener);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//关闭连接
	public void disconnect() {
		try {
			this.connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
